<template>
  <div>
    <Breadcrumb :current="t('menu.friends')" />
    <div class="flex flex-col">
      <div class="post-header">
        <h1 class="post-title text-white uppercase">{{ t('titles.friends') }}</h1>
      </div>
      <div class="main-grid">
        <div class="relative space-y-5">
          <div class="bg-ob-deep-800 p-4 lg:p-14 rounded-2xl shadow-xl mb-8 lg:mb-0">
            <el-row :gutter="36">
              <template v-for="link in links" :key="link.id">
                <el-col :span="8" :xs="{ span: 20, offset: 2 }" class="mb-3">
                  <el-card shadow="never" class="shadow-md">
                    <div class="block">
                      <el-avatar :size="60" :src="link.linkAvatar" />
                    </div>
                    <div class="info">
                      <a :href="link.linkAddress" target="_blank">
                        <div class="link-name font-semibold">{{ link.linkName }}</div>
                      </a>
                      <div class="link-intro truncate">{{ link.linkIntro }}</div>
                    </div>
                  </el-card>
                </el-col>
              </template>
            </el-row>
          </div>
          <div class="post-html text-center">
            <p
                v-html="`需要交换友链的可在下方点击按钮提交申请💖<br><br>友链信息展示需要，你的信息格式要包含：名称、头像、链接、介绍。`"
            />
            <button class="apply-button" @click="linkState.showLinkForm = true">
              申请友链
            </button>
          </div>
          <Comment />
        </div>
        <div class="col-span-1">
          <Sidebar>
            <Profile />
          </Sidebar>
        </div>
      </div>
    </div>
    <!-- 申请友链对话框 -->
    <el-dialog v-model="linkState.showLinkForm" title="申请友链" width="30%" :fullscreen="isMobile">
      <el-form ref="applyForm" :model="linkState.linkForm" :rules="linkState.rules">
        <el-form-item label="名称" class="mt-5" prop="name">
          <el-input v-model="linkState.linkForm.name"></el-input>
        </el-form-item>
        <el-form-item label="头像" class="mt-5" prop="avatar">
          <el-input v-model="linkState.linkForm.avatar"></el-input>
        </el-form-item>
        <el-form-item label="链接" class="mt-5" prop="address">
          <el-input v-model="linkState.linkForm.address"></el-input>
        </el-form-item>
        <el-form-item label="介绍" class="mt-5" prop="intro">
          <el-input v-model="linkState.linkForm.intro"></el-input>
        </el-form-item>
        <el-form-item class="button-container">
          <el-button
              type="primary"
              size="large"
              class="mx-auto mt-3"
              :disabled="linkState.isSubmitting"
              @click="submitLink"
          >
            {{ linkState.isSubmitting ? '提交中...' : '提交申请' }}
          </el-button>
        </el-form-item>
        <el-form-item class="button-container">
          <el-button class="mx-auto mt-3" @click="linkState.showLinkForm = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, provide, computed, toRefs, onMounted,   getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import { Sidebar, Profile } from '../components/Sidebar';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Comment } from '../components/Comment';
import { useCommentStore } from '@/stores/comment';
import emitter from '@/utils/mitt';
import api from '@/api/api';
export default defineComponent({
  name: 'FriendLink',
  components: { Sidebar, Profile, Breadcrumb, Comment },
  setup() {
    const { t } = useI18n();
    const commentStore = useCommentStore();
    const proxy: any = getCurrentInstance()?.appContext.config.globalProperties;
    const reactiveData = reactive({
      links: '' as any,
      comments: [] as any,
      haveMore: false as any,
      isReload: false as any
    });
    const linkState = reactive({
      isSubmitting: false, // 添加提交状态
      showLinkForm: false,
      linkForm: {
        name: '',
        avatar: '',
        address: '',
        intro: '',
        isreview: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 20, message: '名称长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '请输入头像链接', trigger: 'blur' },
          {
            pattern: /^https?:\/\/.*\.(jpg|jpeg|png|gif)$/i,
            message: '请输入有效的图片URL（支持jpg, jpeg, png, gif格式）',
            trigger: 'blur'
          }
        ],
        address: [
          { required: true, message: '请输入链接', trigger: 'blur' },
          {
            pattern: /^https?:\/\/.+$/i,
            message: '请输入有效的URL或者域名（支持http://或https://）',
            trigger: 'blur'
          }
        ],
        intro: [
          { required: true, message: '请输入介绍', trigger: 'blur' },
          { min: 5, max: 25, message: '介绍长度在 5 到 25 个字符', trigger: 'blur' }
        ]
      }
    });

    const pageInfo = reactive({
      current: 1,
      size: 7
    });
    commentStore.type = 4;
    onMounted(() => {
      fetchLinks();
      fetchComments();
    });
    provide(
        'comments',
        computed(() => reactiveData.comments)
    );
    provide(
        'haveMore',
        computed(() => reactiveData.haveMore)
    );
    emitter.on('friendLinkFetchComment', () => {
      pageInfo.current = 1;
      reactiveData.isReload = true;
      fetchComments();
    });
    emitter.on('friendLinkFetchReplies', (index) => {
      fetchReplies(index);
    });
    emitter.on('friendLinkLoadMore', () => {
      fetchComments();
    });

    const fetchLinks = () => {
      api.getFriendLink().then(({ data }) => {
        reactiveData.links = data.data;
      });
    };

    const fetchComments = () => {
      const params = {
        type: 4,
        topicId: null,
        current: pageInfo.current,
        size: pageInfo.size
      };
      api.getComments(params).then(({ data }) => {
        if (reactiveData.isReload) {
          reactiveData.comments = data.data.records;
          reactiveData.isReload = false;
        } else {
          reactiveData.comments.push(...data.data.records);
        }
        if (data.data.count <= reactiveData.comments.length) {
          reactiveData.haveMore = false;
        } else {
          reactiveData.haveMore = true;
        }
        pageInfo.current++;
      });
    };

    const fetchReplies = (index: any) => {
      api.getRepliesByCommentId(reactiveData.comments[index].id).then(({ data }) => {
        reactiveData.comments[index].replyDTOs = data.data;
      });
    };
    const submitLink = () => {
      const { name, avatar, address, intro } = linkState.linkForm;

      // 简单的表单验证
      if (!name || name.length < 2 || name.length > 20) {
        proxy.$notify({
          title: 'Warning',
          message: '名称长度在 2 到 20 个字符',
          type: 'warning'
        });
        return;
      }

      if (!avatar || !/^https?:\/\/.*\.(jpg|jpeg|png|gif)$/i.test(avatar)) {
        proxy.$notify({
          title: 'Warning',
          message: '请输入有效的图片URL（支持jpg, jpeg, png, gif格式）',
          type: 'warning'
        });
        return;
      }

      if (!address || !/^https?:\/\/.+$/i.test(address)) {
        proxy.$notify({
          title: 'Warning',
          message: '请输入有效的URL或者域名',
          type: 'warning'
        });
        return;
      }

      if (!intro || intro.length < 5 || intro.length > 25) {
        proxy.$notify({
          title: 'Warning',
          message: '介绍长度在 5 到 25 个字符',
          type: 'warning'
        });
        return;
      }
      // 表单验证通过，设置提交状态
      linkState.isSubmitting = true;

      // 表单验证通过，提交申请
      const params = {
        linkName: name,
        linkAvatar: avatar,
        linkAddress: address,
        linkIntro: intro,
        isReview: linkState.linkForm.isreview
      };

      api.submitFriendLink(params).then((response) => {
        if (response.data.flag) {
          linkState.showLinkForm = false;
          proxy.$notify({
            title: 'Success',
            message: '申请成功，我们会尽快处理您的申请。',
            type: 'success'
          });
        } else {
          proxy.$notify({
            title: 'Error',
            message: '申请失败，请稍后再试。',
            type: 'error'
          });
        }
      }).catch((error) => {
        console.error('提交申请时发生错误:', error);
        proxy.$notify({
          title: 'Error',
          message: '申请失败，请稍后再试。',
          type: 'error'
        });
      });
    };


    const isMobile = computed(() => {
      return window.innerWidth <= 768; // 你可以根据需要调整这个值
    });

    return {
      ...toRefs(reactiveData),
      t,
      linkState,
      isMobile,
      submitLink
    };
  }
});
</script>

<style lang="scss" scoped>
.block {
  display: inline-block;
  width: 24%;
}
.info {
  display: inline-block;
  width: 76%;
  height: 100%;
}
.link-name {
  margin-left: 20px;
  margin-bottom: 5px;
  margin-top: 2px;
  color: var(--text-normal);
  font-size: large;
}
.link-intro {
  margin-left: 20px;
  margin-bottom: 1px;
  color: var(--text-normal);
}
.el-card {
  background: var(--background-primary);
  border-radius: 10px;
  border: 0;
}
.apply-button {
  display: block;
  margin: 20px auto;
  padding: 10px 20px;
  background-color: #49BDAD;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>
